package cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/** ABA的问题，展示
 * @author dengzhiyuan
 * @version 1.0
 * @time 2021/3/22 17:02
 */
public class CasABATest {

    public static AtomicInteger a = new AtomicInteger(1);

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("操作线程="+Thread.currentThread().getName()+",初始值="+a.get());
                try {
                    int expectNum = a.get();
                    int newNum = expectNum +1;
                    TimeUnit.SECONDS.sleep(1);
                    boolean b = a.compareAndSet(expectNum, newNum);
                    System.out.println("操作线程="+Thread.currentThread().getName()+",CAS操作：="+b);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"主线程");
        thread.start();

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int expectNum = a.get();
                    int newNum = expectNum +1;
                    TimeUnit.MILLISECONDS.sleep(100);
                    a.incrementAndGet();
                    System.out.println("操作线程="+Thread.currentThread().getName()+",[incrementAndGet]="+a.get());
                    a.decrementAndGet();
                    System.out.println("操作线程="+Thread.currentThread().getName()+",[decrementAndGet]="+a.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"干扰线程");
        thread2.start();
    }


}
